package com.qen.sheji.daili;

import cn.hutool.core.lang.Console;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGlib代码模式需要实现MethodInterceptor，并在intercept方法中实现真实对象的功能增强，代码如下
 */
public class CglibProxyFactory implements MethodInterceptor {

    private Object target;

    public CglibProxyFactory(Object target) {
        this.target = target;
    }

    public Object getProxyInstance() {
        Enhancer en = new Enhancer();
        en.setSuperclass(target.getClass());
        en.setCallback(this);
        return en.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Console.log("开始拦截");
        Object returnValue = method.invoke(target, objects);
        Console.log("结束拦截");
        return returnValue;
    }
}
